package com.example.safelib

import android.app.Application
import android.widget.Toast
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.example.baselib.BaseViewModel
import com.example.baselib.constants.MyConstants
import com.example.baselib.databean.Unitinfo
import com.example.baselib.databean.UserData
import com.example.baselib.utils.TimeUtils
import com.example.safelib.bean.*
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import org.json.JSONObject
import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.HashMap


/**
 * Author: sxygsj
 * Date: 2020/4/23 11:56
 * Description: Safe
 * History:
 * <author> <time> <version> <desc>
 * 作者姓名 修改时间 版本号 描述
 */
class SafeViewModel(application: Application) : BaseViewModel(application) {

    private val repository = SafeRepository()
    private val userData: UserData = MyConstants.userData
    private val alarmData: MutableLiveData<List<SafeAlarmBean>> by lazy { MutableLiveData<List<SafeAlarmBean>>().also { loadAlarmData() } }
    private val senInfoData: MutableLiveData<List<SafeSenSorBean>> by lazy { MutableLiveData<List<SafeSenSorBean>>() }
    private val sensorList: MutableLiveData<SafeSerList> by lazy { MutableLiveData<SafeSerList>()}
    private lateinit var lineData: MutableLiveData<SafeLineCharList>
    private val reportList: MutableLiveData<List<SafeReportBean>> by lazy { MutableLiveData<List<SafeReportBean>>().also { loadReportList() } }
    private val sensorMoreData: MutableLiveData<SafeSenSorMoreBean> by lazy { MutableLiveData<SafeSenSorMoreBean>() }
    val lineInfoList: ArrayList<SafeLineInfoBean> by lazy { ArrayList<SafeLineInfoBean>() }
    val lineDataList: ArrayList<SafeLineCharList> by lazy { ArrayList<SafeLineCharList>() }
    var senType: String = ""
    var reportDate = Calendar.getInstance()
    private  var unitinfo: Map<String,String> = HashMap<String,String>()
    fun setUnitInfo(unitinfo: Map<String,String>){
        this.unitinfo=unitinfo
    }
    fun getUnitInfo():  Map<String,String> {
        return unitinfo
    }
    fun getUserData(): UserData {
        return userData
    }

    fun getAlarmData(): LiveData<List<SafeAlarmBean>> {
        return alarmData
    }

    fun loadAlarmData() = launchUI {
        val result = repository.loadAlarmData(userData.token,  unitinfo.getValue("unitcode"))
        val type = object : TypeToken<List<SafeAlarmBean>>() {}.type
        alarmData.value = Gson().fromJson<List<SafeAlarmBean>>(result.body()?.data, type)
    }

    fun getSenList(): LiveData<SafeSerList> {
        return sensorList
    }

    fun getSenInfo(): LiveData<List<SafeSenSorBean>> {
        return senInfoData
    }

    fun getLineChartData(): LiveData<SafeLineCharList> {
        lineData = MutableLiveData()
        return lineData
    }

    fun getReoprtData(): LiveData<List<SafeReportBean>> {
        return reportList
    }

    fun getSenMoreInfo(sensornum: String): LiveData<SafeSenSorMoreBean> {
        loadSensorInfo(sensornum)
        return sensorMoreData
    }

    fun loadSensorInfo(sensornum: String) = launchUI {
        val result =
            repository.loadSensorInfo(userData.token,  unitinfo.getValue("unitcode"), sensornum)
        val type = object : TypeToken<List<SafeSenSorMoreBean>>() {}.type
        sensorMoreData.value =
            Gson().fromJson<List<SafeSenSorMoreBean>>(result.body()?.data, type)[0]
    }

    /**
     * 单独用来list 获取列表监测数据
     */
    fun loadSenInfo() = launchUI {
        val loadSenSor = loadSenSor()
        senInfoData.value=loadSenSor

    }
    suspend fun loadSenName(): List<SafeSenNameBean> {
        val result = repository.loadSenName(userData.token,  unitinfo.getValue("unitcode"))
        val type = object : TypeToken<List<SafeSenNameBean>>() {}.type
        return Gson().fromJson<List<SafeSenNameBean>>(result.body()?.data, type)
    }

    suspend fun loadSenSor(): List<SafeSenSorBean> {
        val result = repository.loadSenInfo(userData.token,  unitinfo.getValue("unitcode"))
        val type = object : TypeToken<List<SafeSenSorBean>>() {}.type
        return Gson().fromJson<List<SafeSenSorBean>>(result.body()?.data, type)
    }

    /**
     * @Description: [加载传感器列表]
     * @Param:
     * @Return:
     * @PS：有问题 不需要请求两个  loadSenSor  应该就可以 按sensorname分类
     */
    fun loadSenList() = launchUI {
        val info = loadSenSor()
        senInfoData.value=info
        //利用协程的挂起 执行完网络请求有数据后才继续往下执行
        val name = loadSenName()
        val senNameList = ArrayList<SafeSenNameBean>()
        val iterator = name.iterator()
        while (iterator.hasNext()) {
            senNameList.add(iterator.next())
        }
        val senNumList = ArrayList<List<String>>()
        val h = HashSet<String>()
        for (i in senNameList.indices) {
            val name = senNameList[i].sensorname
            val numList = ArrayList<String>()
            for (j in info.indices) {
                if (info[j].sensorname != null && info[j].sensorname == name) {
                    numList.add(info[j].sensorplace)
                }
            }
            h.clear()
            h.addAll(numList)
            numList.clear()
            numList.addAll(h)
            senNumList.add(numList)
        }
        sensorList.value = SafeSerList(senNameList, senNumList)
    }

    fun loadLineChart(map: HashMap<String, String>) = launchUI {
        var data = loadLineData(map)
        lineData.value = data
        if(!data.lineValue.isNullOrEmpty()){
            val pos=lineInfoList.indexOf(data.lineInfo)
            if (pos!=-1){
                lineInfoList[pos] = data.lineInfo
                lineDataList[pos] = data
            }else{
                lineDataList.add(data)
                lineInfoList.add(data.lineInfo)
            }

        }


    }

    fun loadAlarmLine(map: HashMap<String, String>) = launchUI {
        var data = loadLineData(map)
        lineData.value = data
    }

    suspend fun loadLineData(map: HashMap<String, String>): SafeLineCharList {
        map["unitcode"] =  unitinfo.getValue("unitcode")
        val result = repository.loadLineChart(userData.token, map)
        val json = JSONObject(result.body()?.string())
        val dataType = object : TypeToken<List<SafeLinCharBean>>() {}.type
        val data =
            Gson().fromJson<List<SafeLinCharBean>>(json.getJSONArray("data").toString(), dataType)
        val infoType = object : TypeToken<List<SafeLineInfoBean>>() {}.type
        val sensorInfo = Gson().fromJson<List<SafeLineInfoBean>>(
            json.getJSONArray("sensorInfo").toString(),
            infoType
        )[0]
        return SafeLineCharList(data, sensorInfo)
    }

    fun loadReportList() = launchUI {
        val result = repository.loadReportData(
            userData.token,
            unitinfo.getValue("unitcode"),
            TimeUtils.sdf.format(reportDate.time)
        )
        val type = object : TypeToken<List<SafeReportBean>>() {}.type
        reportList.value = Gson().fromJson<List<SafeReportBean>>(result.body()?.data, type)
        Toast.makeText(getApplication(),"查询成功", Toast.LENGTH_SHORT).show()
    }


}
